using System;
using System.Data;
using System.Collections;
using System.Collections.Generic;

using Framework;

namespace SchemaMonitor
{
    [Serializable()]
    public partial class CPhotoHash : CBaseDynamic, IComparable<CPhotoHash>
    {
        #region Constructors
        //Public (Copy Constructor)
        public CPhotoHash(CPhotoHash original, CDataSrc target)
        {
            //Database Connection
            m_dataSrc = target;

            //Copy fields
            _photoMd5 = original.PhotoMd5;
            _photoParentMD5 = original.PhotoParentMD5;
            _photoBlob = original.PhotoBlob;
            _photoWidth = original.PhotoWidth;
            _photoHeight = original.PhotoHeight;
            _photoCreated = original.PhotoCreated;
            _photoSize = original.PhotoSize;
            _photoCaptions = original.PhotoCaptions;
            _photoFileNames = original.PhotoFileNames;
            _photoThumb48x48_Int16ProtoGz = original.PhotoThumb48x48_Int16ProtoGz;
            _photoThumbMD5 = original.PhotoThumbMD5;
        }

        //Protected (Datareader/Dataset)
        protected CPhotoHash(CDataSrc dataSrc, IDataReader dr) : base(dataSrc, dr) {}
        protected CPhotoHash(CDataSrc dataSrc, DataRow     dr) : base(dataSrc, dr) {}
        #endregion

        #region Default Values
        protected override void InitValues_Auto()
        {
            //Null-Equivalent values (except String.Empty, as nulls tend to be inconvenient for string types)
            _photoMd5 = Guid.Empty;
            _photoParentMD5 = Guid.Empty;
            _photoBlob = new byte[]{};
            _photoWidth = int.MinValue;
            _photoHeight = int.MinValue;
            _photoCreated = DateTime.MinValue;
            _photoSize = long.MinValue;
            _photoCaptions = string.Empty;
            _photoFileNames = string.Empty;
            _photoThumb48x48_Int16ProtoGz = new byte[]{};
            _photoThumbMD5 = Guid.Empty;
        }
        #endregion

        #region Members
        protected Guid _photoMd5;
        protected Guid _photoParentMD5;
        protected byte[] _photoBlob;
        protected int _photoWidth;
        protected int _photoHeight;
        protected DateTime _photoCreated;
        protected long _photoSize;
        protected string _photoCaptions;
        protected string _photoFileNames;
        protected byte[] _photoThumb48x48_Int16ProtoGz;
        protected Guid _photoThumbMD5;
        #endregion

        #region Properties - Column Values
        //Primary Key Column (ReadOnly)
        public Guid PhotoMd5
        {   
            get { return _photoMd5; } 
            set 
            { 
                if (!m_insertPending && _photoMd5 != value)
                {
                    DataSrc.Update(new CNameValueList("PhotoMd5", value), new CWhere(TABLE_NAME, new CCriteria("PhotoMd5", _photoMd5), null));
                    CacheClear();
                }
                _photoMd5 = value;
            }    
        }

        //Table Columns (Read/Write)
        public Guid PhotoParentMD5    {   get { return _photoParentMD5; } set { _photoParentMD5 = value; }    }
        public byte[] PhotoBlob    {   get { return _photoBlob; } set { _photoBlob = value; }    }
        public int PhotoWidth    {   get { return _photoWidth; } set { _photoWidth = value; }    }
        public int PhotoHeight    {   get { return _photoHeight; } set { _photoHeight = value; }    }
        public DateTime PhotoCreated    {   get { return _photoCreated; } set { _photoCreated = value; }    }
        public long PhotoSize    {   get { return _photoSize; } set { _photoSize = value; }    }
        public string PhotoCaptions    {   get { return _photoCaptions; } set { _photoCaptions = value; }    }
        public string PhotoFileNames    {   get { return _photoFileNames; } set { _photoFileNames = value; }    }
        public byte[] PhotoThumb48x48_Int16ProtoGz    {   get { return _photoThumb48x48_Int16ProtoGz; } set { _photoThumb48x48_Int16ProtoGz = value; }    }
        public Guid PhotoThumbMD5    {   get { return _photoThumbMD5; } set { _photoThumbMD5 = value; }    }

        //View Columns (ReadOnly)

        #endregion

        #region MustOverride Methods
        //Schema Information
        public const string TABLE_NAME      = "PhotoHash";
        public const string VIEW_NAME       = "vwPhotoHashLite";         //Used to override this.ViewName { get }
        public const string ORDER_BY_COLS   = "PhotoCreated";   //See the CompareTo method below (Sql-based sorting should match In-Memory sorting)
        public const string SORTING_COLUMN  = "";
        public override string TableName {    get { return TABLE_NAME; } }
        protected override string ViewName {    get {   return VIEW_NAME;    }    }
        protected override string OrderByColumns {    get { return ORDER_BY_COLS; } }

        //CompareTo Interface (Default Sort Order)
        public int CompareTo(CPhotoHash other) {   return this.PhotoCreated.CompareTo(other.PhotoCreated) ;  }

        //Primary Key Information
        public const string PRIMARY_KEY_NAME = "PhotoMd5";
        protected override bool InsertPrimaryKey {  get { return true;    }   }
        protected override string PrimaryKeyName {  get { return PRIMARY_KEY_NAME;    }    }
        protected override object PrimaryKeyValue 
        {
              get { return _photoMd5; }
              set { _photoMd5 = (Guid)value; }
        }

        //Factory Methods - Object
        protected override CBase MakeFrom(DataRow row)      {   return new CPhotoHash(this.DataSrc, row);  }
        protected override CBase MakeFrom(IDataReader dr)   {   return new CPhotoHash(this.DataSrc, dr);   }

        //Factory Methods - List
        protected override IList MakeList()                 {   return new CPhotoHashList();               }
        protected override IList MakeList(int capacity)     {   return new CPhotoHashList(capacity);       }

        //Convert from ADO to .Net
        protected override void ReadColumns(IDataReader dr)
        {
            _photoMd5 = CAdoData.GetGuid(dr, "PhotoMd5");
            _photoParentMD5 = CAdoData.GetGuid(dr, "PhotoParentMD5");
            _photoBlob = CAdoData.GetBytes(dr, "PhotoBlob");
            _photoWidth = CAdoData.GetInt(dr, "PhotoWidth");
            _photoHeight = CAdoData.GetInt(dr, "PhotoHeight");
            _photoCreated = CAdoData.GetDate(dr, "PhotoCreated");
            _photoSize = CAdoData.GetLong(dr, "PhotoSize");
            _photoCaptions = CAdoData.GetStr(dr, "PhotoCaptions");
            _photoFileNames = CAdoData.GetStr(dr, "PhotoFileNames");
            _photoThumb48x48_Int16ProtoGz = CAdoData.GetBytes(dr, "PhotoThumb48x48_Int16ProtoGz");
            _photoThumbMD5 = CAdoData.GetGuid(dr, "PhotoThumbMD5");
        }
        protected override void ReadColumns(DataRow dr)
        {
            _photoMd5 = CAdoData.GetGuid(dr, "PhotoMd5");
            _photoParentMD5 = CAdoData.GetGuid(dr, "PhotoParentMD5");
            _photoBlob = CAdoData.GetBytes(dr, "PhotoBlob");
            _photoWidth = CAdoData.GetInt(dr, "PhotoWidth");
            _photoHeight = CAdoData.GetInt(dr, "PhotoHeight");
            _photoCreated = CAdoData.GetDate(dr, "PhotoCreated");
            _photoSize = CAdoData.GetLong(dr, "PhotoSize");
            _photoCaptions = CAdoData.GetStr(dr, "PhotoCaptions");
            _photoFileNames = CAdoData.GetStr(dr, "PhotoFileNames");
            _photoThumb48x48_Int16ProtoGz = CAdoData.GetBytes(dr, "PhotoThumb48x48_Int16ProtoGz");
            _photoThumbMD5 = CAdoData.GetGuid(dr, "PhotoThumbMD5");
        }
		
        #endregion

        #region Queries - SelectAll/SelectWhere (inherited methods, cast only)
        //Normally used to load the cache
        public    new CPhotoHashList SelectAll()                                                                           {   return (CPhotoHashList)base.SelectAll();        }
        public    new CPhotoHashList SelectAll(string orderBy)                                                             {   return (CPhotoHashList)base.SelectAll(orderBy); }

		//Sometimes use a custom query to load the cache
		public new CPhotoHashList SelectWhere(string colName, ESign sign, object colValue)                              {   return (CPhotoHashList)base.SelectWhere(colName, sign, colValue);                  }
        protected new CPhotoHashList SelectWhere(CCriteria where)                                                          {   return (CPhotoHashList)base.SelectWhere(where);                                    }
        protected new CPhotoHashList SelectWhere(CCriteriaList where)                                                      {   return (CPhotoHashList)base.SelectWhere(where);                                    }
        protected new CPhotoHashList SelectWhere(CCriteriaList where, string tableOrJoin)                                  {   return (CPhotoHashList)base.SelectWhere(where, tableOrJoin, this.OrderByColumns);  }
        protected new CPhotoHashList SelectWhere(CCriteriaList where, string tableOrJoin, string orderBy)                  {   return (CPhotoHashList)base.SelectWhere(where, tableOrJoin, orderBy);              }
        [Obsolete("Arbitrary where-clause is not necessary portable or safe from sql injection attacks. Consider using the parameterised query interfaces (or a stored proc)")]
        protected new CPhotoHashList SelectWhere(string unsafeWhereClause)                                                 {   return (CPhotoHashList)base.SelectWhere(unsafeWhereClause);                        }
        protected     CPhotoHashList SelectById(Guid photoMd5)                                               {   return (CPhotoHashList)base.SelectById(photoMd5);                    }
        protected     CPhotoHashList SelectByIds(List<Guid> ids)                                         {   return (CPhotoHashList)base.SelectByIds(ids);                                      }

		//Select Queries - Paged
		public new CPhotoHashList SelectAll(  CPagingInfo pi)                                               {    return (CPhotoHashList)base.SelectAll(  pi);                          }
        public new CPhotoHashList SelectWhere(CPagingInfo pi, string name, ESign sign, object value)        {    return (CPhotoHashList)base.SelectWhere(pi, name, sign, value);       }
        protected new CPhotoHashList SelectWhere(CPagingInfo pi, CCriteria criteria)                           {    return (CPhotoHashList)base.SelectWhere(pi, criteria);                }
        protected new CPhotoHashList SelectWhere(CPagingInfo pi, CCriteriaList criteria)                       {    return (CPhotoHashList)base.SelectWhere(pi, criteria);                }
        protected new CPhotoHashList SelectWhere(CPagingInfo pi, CCriteriaList criteria, string viewOrJoin)    {    return (CPhotoHashList)base.SelectWhere(pi, criteria, viewOrJoin);    }

        //Select Queries - Transactional (Internal scope for use in cascade deletes)
        internal new CPhotoHashList SelectAll(                                                                                           IDbTransaction tx)  {    return (CPhotoHashList)base.SelectAll(                                                 tx);    }
        internal new CPhotoHashList SelectAll(string orderBy,                                                                            IDbTransaction tx)  {    return (CPhotoHashList)base.SelectAll(orderBy,                                         tx);    }
        internal new CPhotoHashList SelectWhere(string columnName,               object columnValue,                                     IDbTransaction tx)  {    return (CPhotoHashList)base.SelectWhere(columnName,              columnValue,          tx);    }
        internal new CPhotoHashList SelectWhere(string columnName,   ESign sign, object columnValue,                                     IDbTransaction tx)  {    return (CPhotoHashList)base.SelectWhere(columnName,    sign,     columnValue,          tx);    }
        internal new CPhotoHashList SelectWhere(                             CCriteria     criteria,                                     IDbTransaction tx)  {    return (CPhotoHashList)base.SelectWhere(               criteria,                       tx);    }
        internal new CPhotoHashList SelectWhere(                             CCriteriaList criteria,                                     IDbTransaction tx)  {    return (CPhotoHashList)base.SelectWhere(               criteria,                       tx);    }
        internal new CPhotoHashList SelectWhere(                             CCriteriaList criteria, string tableOrJoin,                 IDbTransaction tx)  {    return (CPhotoHashList)base.SelectWhere(               criteria, tableOrJoin,          tx);    }
        internal new CPhotoHashList SelectWhere(                             CCriteriaList criteria, string tableOrJoin, string orderBy, IDbTransaction tx)  {    return (CPhotoHashList)base.SelectWhere(               criteria, tableOrJoin,          tx);    }
        internal     CPhotoHashList SelectById(Guid photoMd5,                                                              IDbTransaction tx)  {    return (CPhotoHashList)base.SelectById(photoMd5,                         tx);    }
        internal     CPhotoHashList SelectByIds(List<Guid> ids,                                                        IDbTransaction tx)  {    return (CPhotoHashList)base.SelectByIds(ids,                                           tx);    }

        //Select Queries - Stored Procs
        protected new CPhotoHashList MakeList(string storedProcName,                           IDbTransaction txOrNull)    {   return (CPhotoHashList)base.MakeList(storedProcName,             txOrNull);  }
        protected new CPhotoHashList MakeList(string storedProcName, object[] parameters,      IDbTransaction txOrNull)    {   return (CPhotoHashList)base.MakeList(storedProcName, parameters, txOrNull);  }
        protected new CPhotoHashList MakeList(string storedProcName, CNameValueList parameters,IDbTransaction txOrNull)    {   return (CPhotoHashList)base.MakeList(storedProcName, parameters, txOrNull);  }
        protected new CPhotoHashList MakeList(string storedProcName, List<object> parameters,  IDbTransaction txOrNull)    {   return (CPhotoHashList)base.MakeList(storedProcName, parameters, txOrNull);  }
        protected new CPhotoHashList MakeList(string storedProcName, int param1,               IDbTransaction txOrNull)    {   return (CPhotoHashList)base.MakeList(storedProcName, param1,     txOrNull);  }
        protected new CPhotoHashList MakeList(string storedProcName, string param1,            IDbTransaction txOrNull)    {   return (CPhotoHashList)base.MakeList(storedProcName, param1,     txOrNull);  }

        //Query Results
        protected new CPhotoHashList MakeList(DataSet              ds) { return (CPhotoHashList)base.MakeList(ds);        }
        protected new CPhotoHashList MakeList(DataTable            dt) { return (CPhotoHashList)base.MakeList(dt);        }
        protected new CPhotoHashList MakeList(DataRowCollection  rows) { return (CPhotoHashList)base.MakeList(rows);      }
        protected new CPhotoHashList MakeList(IDataReader          dr) { return (CPhotoHashList)base.MakeList(dr);        }
        protected new CPhotoHashList MakeList(object           drOrDs) { return (CPhotoHashList)base.MakeList(drOrDs);    }
        protected new CPhotoHashList MakeList(byte[]             gzip) { return (CPhotoHashList)base.MakeList(gzip);      }
        #endregion

        #region Queries - SelectBy[FK] (user-nominated fk/bool columns)
        //Note: These methods should only be used for cascade-deletes, or initialising the cache. Use CPhotoHash.Cache.GetBy... for reqular queries

        //Non-Paged
        protected CPhotoHashList SelectByThumbMD5(Guid photoThumbMD5)    {    return SelectWhere(new CCriteriaList("PhotoThumbMD5", photoThumbMD5));    }

        //Paged
        protected CPhotoHashList SelectByThumbMD5(CPagingInfo pi, Guid photoThumbMD5)    {    return SelectWhere(pi, new CCriteriaList("PhotoThumbMD5", photoThumbMD5));    }

        //Count
        protected int SelectCountByThumbMD5(Guid photoThumbMD5)   {   return SelectCount(new CCriteriaList("PhotoThumbMD5", photoThumbMD5));     }

        //Transactional
        internal CPhotoHashList SelectByThumbMD5(Guid photoThumbMD5, IDbTransaction tx)    {    return SelectWhere(new CCriteriaList("PhotoThumbMD5", photoThumbMD5), tx);    }
        #endregion

        #region Static - Cache Implementation
        public static CPhotoHashList Cache
        {
            get
            {
                CPhotoHashList cache = (CPhotoHashList)CCache.Get(CACHE_KEY);
                if (cache == null)
                {
                    lock (typeof(CPhotoHashList))
                    {
                        cache = (CPhotoHashList)CCache.Get(CACHE_KEY);
                        if (cache == null)
                        {
                            cache = LoadCache();
                            CPhotoHash.Cache = cache;
                        }
                    }
                }
                return cache;
            }
            set
            {
                SetCache(value);   //Not locked, because cache gets cleared at anytime anyway
            }
        }

        //Change Management:
        //Clone, modify, and then replace the cache (threadsafe for anything iterating the collection)
        //Note that internal indices are dicarded each time unless handled in constructor and add/remove overrides
        protected override void CacheDelete()
        {
            if (CacheIsNull)
                return;

            lock (typeof(CPhotoHashList))
            {
                CPhotoHashList temp = new CPhotoHashList(Cache);
                int size = temp.Count;
                temp.Remove(this);
                if (size == temp.Count) //Remove might fail if cache was refreshed with new instances. Use old index
                    temp.Remove(CacheGetById(temp));
                Cache = temp;
            }
        }
        protected override void CacheInsert()
        {
            if (CacheIsNull)
                return;

            lock (typeof(CPhotoHashList))
            {
                CPhotoHashList temp = new CPhotoHashList(Cache);
                temp.Add(this);
                SetCache(temp);
            }
        }
        protected override void CacheUpdate()
        {
            if (CacheIsNull)
                return;

            lock (typeof(CPhotoHashList))
            {
                CPhotoHashList temp = new CPhotoHashList(Cache);
                if (!temp.Contains(this))
                {
					var xx = CacheGetById(temp);
					if (null != xx)
					{
						temp.Remove(xx);
						temp.Add(this);
					}
					SetCache(temp);
				}
			}
        }
        protected override void CacheClear()
        {
            SetCache(null);
        }
        protected static bool CacheIsNull
        {
            get
            {
                return null == CCache.Get(CACHE_KEY);
            }
        }
        #endregion
        #region ToXml
        protected override void ToXml_Autogenerated(System.Xml.XmlWriter w)
        {
            Store(w, "PhotoMd5", this.PhotoMd5);
            Store(w, "PhotoParentMD5", this.PhotoParentMD5);
            Store(w, "PhotoBlob", this.PhotoBlob);
            Store(w, "PhotoWidth", this.PhotoWidth);
            Store(w, "PhotoHeight", this.PhotoHeight);
            Store(w, "PhotoCreated", this.PhotoCreated);
            Store(w, "PhotoSize", this.PhotoSize);
            Store(w, "PhotoCaptions", this.PhotoCaptions);
            Store(w, "PhotoFileNames", this.PhotoFileNames);
            Store(w, "PhotoThumb48x48_Int16ProtoGz", this.PhotoThumb48x48_Int16ProtoGz);
            Store(w, "PhotoThumbMD5", this.PhotoThumbMD5);
        }
        #endregion

    }
}
